//#include <jni.h>
#include "stdafx.h"

//#include "glm/glm.hpp"
#include "sg/sg.h"

#include "Renderer.h"
#include "MatSingleColor.h"

GLuint const Renderer::MAX_VERTICES = 1000;

Renderer::Renderer(){
    //mpMatrix = sgFrustum();
	sgMakeIdentMat4(mmMatrix);

	//allocate buffer
	debug_mat = new MatSingleColor();
	lineList = new RObject(MAX_VERTICES, debug_mat, GL_LINES);
	triList = new RObject(MAX_VERTICES, debug_mat, GL_TRIANGLES);

	LOGI("native renderer created\n");
	LOGI("%d",sizeof(float[4][4]));
}

Renderer::~Renderer(){
	delete lineList;
	delete triList;
	debug_mat = 0;//FIXME: will this delete the pointer?
}

void Renderer::render(const float& elapsed){
	glClearColor(0,0,0,1);
	glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

	//look at matrix
	sgSetVec3(mEyePos, 0, 0, -6);
	sgSetVec3(mEyeAt, 0, 0, 0);
	sgSetVec3(mEyeUp, 0, 1, 0);
	sgMakeLookAtMat4(mvMatrix, mEyePos, mEyeAt, mEyeUp);
	//mpMatrix.setOrtho(-2,2,-2,2,1,100);

	sgMultMat4(mmvpMatrix, mvMatrix, mmMatrix);
	//sgMultMat4(mmvpMatrix, mmMatrix, mvMatrix);
	/*sgMat4 pM;
	mpMatrix.getMat4(pM);
	sgPostMultMat4(mmvpMatrix, pM);//*/
	sgPostMultMat4(mmvpMatrix, mpMatrix.getMat4());

	//sgMakeIdentMat4(mmvpMatrix);

	//sgMultMat4(mmvpMatrix, mpMatrix.getMat4(), mmvpMatrix);
	/*
	for (int i=0;i<4;i++){
		for (int j=i+1;j<4;j++){
			GLfloat a = mmvpMatrix[i][j];
			mmvpMatrix[i][j] = mmvpMatrix[j][i];
			mmvpMatrix[j][i] = a;
		}
	}//*/
	//sgMultMat4(mmvpMatrix, mmvpMatrix, mpMatrix.getMat4());
	//sgTransposeNegateMat4(mmvpMatrix);

	//draw primitives
	debug_mat->initialize_common();

	glDisable(GL_BLEND);
	lineList->render();
	lineList->primitive_count = 0;

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	triList->render();
	triList->primitive_count = 0;
}

void Renderer::render_line(const Vec3& p0, const Vec3& p1, const Color& color){
	int idx = 2*lineList->mat->get_vertex_stride()/sizeof(GLfloat) * lineList->primitive_count;
	copy_to(p0, lineList->vertices, idx);
	idx+= sizeof(Vec3)/sizeof(GLfloat);
	copy_to(color, lineList->vertices, idx);
	idx+= sizeof(Color)/sizeof(GLfloat);
	copy_to(p1, lineList->vertices, idx);
	idx+= sizeof(Vec3)/sizeof(GLfloat);
	copy_to(color, lineList->vertices, idx);
	idx+= sizeof(Color)/sizeof(GLfloat);
	lineList->primitive_count++;
}

void Renderer::render_triangle(const Vec3& p0, const Vec3& p1, const Vec3& p2, const Color& color){
	int idx = 3*triList->mat->get_vertex_stride()/sizeof(GLfloat) * triList->primitive_count;
	copy_to(p0, triList->vertices, idx);
	idx+= sizeof(Vec3)/sizeof(GLfloat);
	copy_to(color, triList->vertices, idx);
	idx+= sizeof(Color)/sizeof(GLfloat);
	copy_to(p1, triList->vertices, idx);
	idx+= sizeof(Vec3)/sizeof(GLfloat);
	copy_to(color, triList->vertices, idx);
	idx+= sizeof(Color)/sizeof(GLfloat);
	copy_to(p2, triList->vertices, idx);
	idx+= sizeof(Vec3)/sizeof(GLfloat);
	copy_to(color, triList->vertices, idx);
	idx+= sizeof(Color)/sizeof(GLfloat);
	triList->primitive_count++;
}


void Renderer::resource_reset(const int& width, const int& height){
	glViewport(0, 0, width, height);
    float ratio = (float) width / height;

    mpMatrix.setFrustum(-ratio, ratio, -1, 1, 1, 100);
    //mpMatrix.setFOV(height, width);
    //mpMatrix.setNearFar(3,100);

    lineList->initialize();

    //mpMatrix = frustum.getMat4()
    //Matrix.frustumM(mProjMatrix, 0, -ratio, ratio, -1, 1, 3, 100);
}

/*
#define  LOG_TAG    "visioncontrol"
#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)

static void printGLString(const char *name, GLenum s) {
    const char *v = (const char *) glGetString(s);
    LOGI("GL %s = %s\n", name, v);
}

static void checkGlError(const char* op) {
    for (GLint error = glGetError(); error; error
            = glGetError()) {
        LOGI("after %s() glError (0x%x)\n", op, error);
    }
}

static const char gVertexShader[] =
    "attribute vec4 vPosition;\n"
    "void main() {\n"
    "  gl_Position = vPosition;\n"
    "}\n";

static const char gFragmentShader[] =
    "precision mediump float;\n"
    "void main() {\n"
    "  gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);\n"
    "}\n";

GLuint loadShader(GLenum shaderType, const char* pSource) {
    GLuint shader = glCreateShader(shaderType);
    if (shader) {
        glShaderSource(shader, 1, &pSource, NULL);
        glCompileShader(shader);
        GLint compiled = 0;
        glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
        if (!compiled) {
            GLint infoLen = 0;
            glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);
            if (infoLen) {
                char* buf = (char*) malloc(infoLen);
                if (buf) {
                    glGetShaderInfoLog(shader, infoLen, NULL, buf);
                    LOGE("Could not compile shader %d:\n%s\n",
                            shaderType, buf);
                    free(buf);
                }
                glDeleteShader(shader);
                shader = 0;
            }
        }
    }
    return shader;
}

GLuint createProgram(const char* pVertexSource, const char* pFragmentSource) {
    GLuint vertexShader = loadShader(GL_VERTEX_SHADER, pVertexSource);
    if (!vertexShader) {
        return 0;
    }

    GLuint pixelShader = loadShader(GL_FRAGMENT_SHADER, pFragmentSource);
    if (!pixelShader) {
        return 0;
    }

    GLuint program = glCreateProgram();
    if (program) {
        glAttachShader(program, vertexShader);
        checkGlError("glAttachShader");
        glAttachShader(program, pixelShader);
        checkGlError("glAttachShader");
        glLinkProgram(program);
        GLint linkStatus = GL_FALSE;
        glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
        if (linkStatus != GL_TRUE) {
            GLint bufLength = 0;
            glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufLength);
            if (bufLength) {
                char* buf = (char*) malloc(bufLength);
                if (buf) {
                    glGetProgramInfoLog(program, bufLength, NULL, buf);
                    LOGE("Could not link program:\n%s\n", buf);
                    free(buf);
                }
            }
            glDeleteProgram(program);
            program = 0;
        }
    }
    return program;
}

GLuint gProgram;
GLuint gvPositionHandle;

bool setupGraphics(int w, int h) {
    printGLString("Version", GL_VERSION);
    printGLString("Vendor", GL_VENDOR);
    printGLString("Renderer", GL_RENDERER);
    printGLString("Extensions", GL_EXTENSIONS);

    LOGI("setupGraphics(%d, %d)", w, h);
    gProgram = createProgram(gVertexShader, gFragmentShader);
    if (!gProgram) {
        LOGE("Could not create program.");
        return false;
    }
    gvPositionHandle = glGetAttribLocation(gProgram, "vPosition");
    checkGlError("glGetAttribLocation");
    LOGI("glGetAttribLocation(\"vPosition\") = %d\n",
            gvPositionHandle);

    glViewport(0, 0, w, h);
    checkGlError("glViewport");
    return true;
}

const GLfloat gTriangleVertices[] = { 0.0f, 0.5f, -0.5f, -0.5f,
        0.5f, -0.5f };

void renderFrame() {
    static float grey;
    grey += 0.01f;
    if (grey > 1.0f) {
        grey = 0.0f;
    }
    glClearColor(grey, grey, grey, 1.0f);
    checkGlError("glClearColor");
    glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
    checkGlError("glClear");

    glUseProgram(gProgram);
    checkGlError("glUseProgram");

    glVertexAttribPointer(gvPositionHandle, 2, GL_FLOAT, GL_FALSE, 0, gTriangleVertices);
    checkGlError("glVertexAttribPointer");
    glEnableVertexAttribArray(gvPositionHandle);
    checkGlError("glEnableVertexAttribArray");
    glDrawArrays(GL_TRIANGLES, 0, 3);
    checkGlError("glDrawArrays");
}
*/
